package simple.framework.util;

import javax.servlet.http.Cookie;

public class cookies
{
  private static String cookiesPath = "/";

  public static String getAttribute(conf argConf, String argKey)
  {
    String tmpstr = "";
    conf tConf = argConf;
    String tKey = argKey;
    Cookie[] tCookies = tConf.request.getCookies();
    if (tCookies != null)
    {
      for (int ti = 0 ; ti < tCookies.length; ti ++)
      {   
        Cookie tCookie = tCookies[ti];
        if (tKey.equals(tCookie.getName()))
        {
          try
          {
            tmpstr = new String(encode.base64decode(tCookie.getValue()), tConf.charset);
          }
          catch(Exception e) {}
        }
      }
    }
    return tmpstr;
  }

  public static void removeAttribute(conf argConf, String argKey)
  {
    conf tConf = argConf;
    String tKey = argKey;
    Cookie[] tCookies = tConf.request.getCookies();
    if (tCookies != null)
    {
      for (int ti = 0 ; ti < tCookies.length; ti ++)
      {   
        Cookie tCookie = tCookies[ti];
        if (tKey.equals(tCookie.getName()))
        {
          tCookie.setMaxAge(0);
          tCookie.setPath(cookiesPath);
          tConf.response.addCookie(tCookie);
        }
      }
    }
  }

  public static void setAttribute(conf argConf, String argKey, String argValue)
  {
    conf tConf = argConf;
    String tKey = argKey;
    String tValue = argValue;
    setAttribute(tConf, tKey, tValue, -1);
  }

  public static void setAttribute(conf argConf, String argKey, String argValue, Integer argMaxAge)
  {
    String tmpstr = "";
    conf tConf = argConf;
    String tKey = argKey;
    String tValue = argValue;
    Integer tMaxAge = argMaxAge;
    try
    {
      Cookie tCookie = new Cookie(tKey, encode.base64encode(tValue.getBytes(tConf.charset)));
      tCookie.setMaxAge(tMaxAge);
      tCookie.setPath(cookiesPath);
      tConf.response.addCookie(tCookie);
    }
    catch(Exception e) {}
  }
}